package com.jzcn.admin.controller.config;

import com.jzcn.admin.base.BaseController;
import com.jzcn.common.dto.file.FileDTO;
import com.jzcn.common.response.ResponseResult;
import com.jzcn.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/api/config/file")
@Api(value = "SysFileController", tags = "文件管理")
public class FileController extends BaseController {

    @Resource
    private SysFileService sysFileService;



    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ResponseResult<FileDTO> uploadUserThree(
            @RequestPart("file") MultipartFile file ,Integer fileType) throws IOException {
        try {

            FileDTO sysFileBo = sysFileService.storeFile(file.getBytes(), file.getOriginalFilename(),fileType,
                    getUserId());
            return new ResponseResult<FileDTO>().success(sysFileBo);
        } catch (Exception e) {
            return new ResponseResult<FileDTO>().failure(e.getMessage());
        }
    }


    @GetMapping("/download/by/fileId")
    @ApiOperation("文件下载")
    public void downloadFile(@RequestParam("fileId") Integer fileId,
                             HttpServletResponse response) throws IOException {
        FileDTO fileBo = sysFileService.getById(fileId);
        String filePath = sysFileService.getLocalPath(fileBo);
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        // 非常重要
        response.reset();
        // 在线打开方式
        // 纯下载方式
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
    }

}
